package model;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;

import data.Task;

public class SimpleModel {
	// Main data
	private String currentFileName  =null;
	private Task currentTask = null;
	// Mutex
	private Object general_mutex = new Object();
//=============================================================================
//-----------CONSTRUCTORS------------------------------------------------------
	public SimpleModel() {}
	
	public SimpleModel(String fileName) throws Exception {
		openFile(fileName);
	}
//=============================================================================
//-----------IMPLEMETATION OF IModel-------------------------------------------	
	public void openFile(String fileName) throws Exception {
		synchronized (general_mutex) {			
			String tmpFileName = currentFileName;
			Task tmpTask = currentTask;
			try {
				parseFile(fileName);
			} catch (Exception ex) {
				currentFileName = tmpFileName;
				currentTask = tmpTask;
				throw ex;
			}
		}		
	}
	
	/**
	 * This methods returns <b>clone</b> task of current task.
	 */
	public Task getCurrentTask() {
		synchronized (general_mutex) {
			if(currentTask == null) return null;
			return currentTask.clone();
		}
	}
	
	public String getCurrentFileName() {
		synchronized (general_mutex) {
			return currentFileName;
		}
	}
		
//=============================================================================
//-----------PRIVATE METHODS---------------------------------------------------	
	public void parseFile(String fileName) throws Exception {
		currentFileName = fileName;
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(fileName);
			final Scanner scanner = new Scanner(inputStream);
			final int actorsNumber = new Integer(scanner.next());
			final int scenesNumber = scanner.nextInt();
			if(actorsNumber <= 0 || scenesNumber <= 0)
				throw new Exception("not positive number of actors or scenes");
			
			final float [] actorsSalary = new float[actorsNumber];
			final boolean [][] actorsScenesRelation = new boolean[actorsNumber][scenesNumber];
			
			for(int i = 0 ; i < actorsNumber ; ++i)
				actorsSalary[i] = scanner.nextFloat();
			
			for(int i = 0 ; i < actorsNumber ; ++i)
				for(int j = 0 ; j < scenesNumber ; ++j)
					actorsScenesRelation[i][j] = scanner.nextInt() != 0;
			
			currentTask = new Task(actorsNumber, scenesNumber, actorsScenesRelation, actorsSalary);
		
		} catch (RuntimeException e) {
			throw new Exception("wrong format of input", e);
		} finally {
			if(inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception ex) {}
			}
		}
	}
}
